package com.lepu.app.fun.mother_circle.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragment;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.knowledge.bean.Article;
import com.lepu.app.fun.mother_circle.adapter.AdapterMotherPost;
import com.lepu.app.fun.mother_circle.bean.BeanMotherTopic;
import com.lepu.app.fun.my.bean.BeanPubContent;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.FocusView;

public class FragmentMotherPost extends BaseFragment implements AsyncRequest,
		OnRefreshListener, OnLoadListener {

	private static final String REQUEST_DATA_FOCUS = "request_data_focus";

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	// 我的主题列表，可以删除主题
	private static final String REQUEST_DELETE_TOPIC = "request_delete_topic";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;

	private static final int MSG_DATA_FOCUS_SUCCESS = 30;

	// ========================================================================
	private static FragmentMotherPost mInstance = null;

	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterMotherPost mDataAdapter = null;
	private ArrayList<BeanPubContent> mDataArrayList = null;
	private int mCurrentPage = 1;
	private boolean mInitDataSuccess = false;

	private View mMainView = null;

	private String mCurrentDate = "";

	private FocusView mFocusViewArticle = null;
	
	private boolean mIsRefreshData = true;

	public static FragmentMotherPost getInstance() {
		return mInstance;
	}

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mInstance = this;
		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.mother_show_fragment, null, false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
		mInstance = null;
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mFocusViewArticle != null) {
			mFocusViewArticle.onResumeViewPager();
		}

		UmengHelper.OnPageStart("3");
	}

	@Override
	public void onPause() {
		super.onPause();

		if (mFocusViewArticle != null) {
			mFocusViewArticle.onPauseViewPager();
		}

		UmengHelper.OnPageEnd("3");
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				// 第一次进入页面获取数据

				showFirstLoadDataLayout(true);
				requestFocus(true);
			}
		}
	}

	private void showHideNoDataLayout(boolean isShow) {
		LinearLayout noDataLayout = (LinearLayout) mMainView
				.findViewById(R.id.noDataLayout);
		if (noDataLayout != null) {
			if (isShow) {
				noDataLayout.setVisibility(View.VISIBLE);
			} else {
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showFirstLoadDataLayout(boolean isShow) {
		LinearLayout firstLoadDataLayout = (LinearLayout) mMainView
				.findViewById(R.id.firstLoadDataLayout);
		if (firstLoadDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}

				LinearLayout noDataLayout = (LinearLayout) mMainView
						.findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);

			} else {
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("ResourceAsColor")
	private void init() {
		mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) mMainView
				.findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		mDataListView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == 0) {
					UniversalImageLoadTool.resume();
				} else {
					UniversalImageLoadTool.pause();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
	}

	// 请求轮播图
	public void requestFocus(boolean isRefreshData) {
		String url = Setting.getArticleListUrl();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);
			params.put("ACIDList", "5");// 5

			params.put("RefreshTime", mCurrentDate);
			params.put("PageIndex", 1);
			params.put("PageSize", 10);
			params.put("SortBy", 1);
			params.put("SortDirection", "DESC");
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_DATA_FOCUS, true,
				false, true);
	}

	// 请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
			mCurrentDate = "";
		}

		// String url = Setting.getTestJsonUrl(page);
		// ApiClient.http_get(url, this, request);

		String url = Setting.getPostListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (MyApplication.getInstance().checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				params.put("UserID", loginInfo.UserID);
			} else {
				params.put("UserID", -1);
			}

			params.put("RefreshTime", mCurrentDate);
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true, false, true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				ArrayList<BeanPubContent> dataList = (ArrayList<BeanPubContent>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					mInitDataSuccess = true;
					mDataArrayList = dataList;

					showHideNoDataLayout(false);
				} else {
					UIHelper.showToast(getActivity(), R.string.no_data);

					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
					showHideNoDataLayout(true);
				}

				if (mDataArrayList == null) {
					mDataArrayList = new ArrayList<BeanPubContent>();
				}

				ImageView tempImageView = new ImageView(getActivity());
				mDataListView.addHeaderView(tempImageView);

				mDataAdapter = new AdapterMotherPost(
						(BaseFragmentActivity) getActivity(), mDataArrayList);
				mDataListView.setAdapter(mDataAdapter);

				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				// 第一次请求用这个
				showFirstLoadDataLayout(false);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				showFirstLoadDataLayout(false);
				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanPubContent> dataMoreList = (ArrayList<BeanPubContent>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(getActivity(), R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;

			case MSG_DATA_FOCUS_SUCCESS:
				ArrayList<Article> articleList = (ArrayList<Article>) msg.obj;
				if (articleList != null && articleList.size() > 0) {

					if (mFocusViewArticle != null) {
						mDataListView.removeHeaderView(mFocusViewArticle);
					}

					mFocusViewArticle = new FocusView(getActivity(),
							articleList,
							Utils.getBannerHeight25To8(getActivity()), null, 0,
							R.drawable.index_banner_icon_default,mGoogleRefreshLayout);

					mDataListView.addHeaderView(mFocusViewArticle);
				}

				if(mIsRefreshData){
					// 请求列表数据
					request(false);
				}else{
					if(mDataAdapter != null){
						mDataAdapter.notifyDataSetChanged();
					}
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		// requestFocus();
		request(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			mCurrentDate = BeanMotherTopic.parseJsonDate((String) data);
			// 解析json data
			ArrayList<BeanPubContent> dataArraylist = BeanPubContent
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mCurrentDate = BeanMotherTopic.parseJsonDate((String) data);
			// 解析json data more
			ArrayList<BeanPubContent> dataMoreArraylist = BeanPubContent
					.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					BeanPubContent item = dataMoreArraylist.get(i);
					mDataArrayList.add(item);
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_FOCUS)) {
			// 解析json data
			ArrayList<Article> dataArraylist = Article
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_FOCUS_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} else if (object.equals(REQUEST_DATA_FOCUS)) {
			mHandler.sendEmptyMessage(MSG_DATA_FOCUS_SUCCESS);
		} else if (object.equals(REQUEST_DELETE_TOPIC)) {
			// main thread

			MainTabActivity.getInstance().hideProgressDialog();
		}
	}

}
